package com.ruoyi.safe.common;

/**
 * @Auther: lihongming
 * @Date: 2023-11-06 10:21
 * @Description: com.ruoyi.safe.common
 * @Version: 1.0
 */

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.config.MinIoProperties;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileTypeUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.file.MinIoUtil;
import com.ruoyi.common.utils.uuid.Seq;
import com.ruoyi.safe.domain.BizEducateDocAttach;
import com.ruoyi.safe.domain.BizOrgImg;
import com.ruoyi.safe.domain.BizSafeAttach;
import com.ruoyi.safe.domain.BizSafeDocAttach;
import com.ruoyi.safe.domain.vo.BizEducateDocAttachVO;
import com.ruoyi.safe.service.IBizEducateDocAttachService;
import com.ruoyi.safe.service.IBizOrgImgService;
import com.ruoyi.safe.service.IBizSafeAttachService;
import com.ruoyi.safe.service.IBizSafeDocAttachService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * PC端上传
 *
 * @author ruoyi
 */
@Slf4j
@RestController
@RequestMapping("/safeUploader")
public class uploader {
    @Autowired
    MinIoProperties minIoProperties;
    @Autowired
    IBizSafeAttachService bizSafeAttachService;
    @Autowired
    IBizOrgImgService bizOrgImgService;
    @Autowired
    IBizSafeDocAttachService bizSafeDocAttachService;
    @Autowired
    IBizEducateDocAttachService bizEducateDocAttachService;
    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     */
    @GetMapping("/download")
    public void fileDownload(String fileName, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            MinIoUtil.download(minIoProperties.getBucketName(), fileName, response);
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) throws Exception {
        try {
            if (!file.isEmpty()) {
                if (!FileUtils.checkAllowDownload(file.getOriginalFilename())) {
                    throw new Exception(StringUtils.format("文件名称({})非法，不允许上传。 ", file.getOriginalFilename()));
                }
                // 上传并返回新文件名称
                String suffixName = FileTypeUtils.getFileType(file);
                Long userId = SecurityUtils.getLoginUser().getUserId();

                String fileName = StringUtils.format("{}_{}_{}.{}",
                        FilenameUtils.getBaseName(file.getOriginalFilename()),
                        userId,
                        Seq.getId(Seq.uploadSeqType), suffixName);
                String url = MinIoUtil.upload(minIoProperties.getBucketName(), fileName, file.getInputStream());
                AjaxResult ajax = AjaxResult.success();
                ajax.put("url", url);
                ajax.put("fileName", fileName);
                return ajax;
            } else {
                return AjaxResult.error("上传文件不能为空，请联系管理员");
            }
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 检查图片上传
     */
    @PostMapping("/uploadSafe")
    public AjaxResult uploadSafe(@RequestParam("file") MultipartFile file, @RequestParam("projectId") Long projectId) throws Exception {
        try {
            if (!file.isEmpty()) {
                if (!FileUtils.checkAllowDownload(file.getOriginalFilename())) {
                    throw new Exception(StringUtils.format("文件名称({})非法，不允许上传。 ", file.getOriginalFilename()));
                }
                // 上传并返回新文件名称
                String suffixName = FileTypeUtils.getFileType(file);
                String fileName = StringUtils.format("{}_{}_{}.{}",
                        FilenameUtils.getBaseName(file.getOriginalFilename()),
                        SecurityUtils.getUserId(),
                        Seq.getId(Seq.uploadSeqType), suffixName);
                String url = MinIoUtil.upload(minIoProperties.getBucketName(), fileName, file.getInputStream());
                AjaxResult ajax = AjaxResult.success();
                ajax.put("url", url);
                ajax.put("bucket", minIoProperties.getBucketName());
                ajax.put("fileName", fileName);
                BizSafeAttach bizSafeAttach = BizSafeAttach.builder()
                        .id(IdUtil.getSnowflakeNextId())
                        .bucket(minIoProperties.getBucketName())
                        .name(fileName)
                        .size(file.getSize())
                        .type(file.getContentType())
                        .projectId(projectId)
                        .build();
                bizSafeAttach.setCreateBy(SecurityUtils.getUsername());
                bizSafeAttach.setCreateTime(DateUtils.getNowDate());
                bizSafeAttachService.insertBizSafeAttachNoLogin(bizSafeAttach);
                Long bizSafeAttachId  = bizSafeAttach.getId();
                ajax.put("fileId", bizSafeAttachId.toString());
                return ajax;
            } else {
                return AjaxResult.error("上传文件不能为空，请联系管理员");
            }
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 组织机构图上传
     */
    @PostMapping("/uploadOrgImg")
    public AjaxResult uploadOrgImg(@RequestParam("file") MultipartFile file, @RequestParam("projectId") Long projectId) throws Exception {
        try {
            if (!file.isEmpty()) {
                if (!FileUtils.checkAllowDownload(file.getOriginalFilename())) {
                    throw new Exception(StringUtils.format("文件名称({})非法，不允许上传。 ", file.getOriginalFilename()));
                }
                // 上传并返回新文件名称
                String suffixName = FileTypeUtils.getFileType(file);
                String fileName = StringUtils.format("{}_{}_{}.{}",
                        FilenameUtils.getBaseName(file.getOriginalFilename()),
                        SecurityUtils.getUserId(),
                        Seq.getId(Seq.uploadSeqType), suffixName);
                String url = MinIoUtil.upload(minIoProperties.getBucketOrgImg(), fileName, file.getInputStream());
                AjaxResult ajax = AjaxResult.success();
                ajax.put("url", url);
                ajax.put("bucket", minIoProperties.getBucketName());
                ajax.put("fileName", fileName);
                //TODO 图片信息入库
                BizOrgImg bizOrgImg = BizOrgImg.builder()
                        .id(IdUtil.getSnowflakeNextId())
                        .bucket(minIoProperties.getBucketOrgImg())
                        .displayName(FilenameUtils.getBaseName(file.getOriginalFilename()))
                        .realName(fileName)
                        .extName(suffixName)
                        .size(file.getSize())
                        .type(file.getContentType())
                        .projectId(projectId)
                        .build();
                bizOrgImg.setCreateBy(SecurityUtils.getUsername());
                bizOrgImg.setCreateTime(DateUtils.getNowDate());
                bizOrgImgService.insertBizOrgImg(bizOrgImg);
                Long bizOrgImgId  = bizOrgImg.getId();
                ajax.put("fileId", bizOrgImgId.toString());
                return ajax;
            } else {
                return AjaxResult.error("上传文件不能为空，请联系管理员");
            }
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 工程内业资料上传
     */
    @PostMapping("/uploadSafeDoc")
    public AjaxResult uploadSafeDoc(@RequestParam("file") MultipartFile file, @RequestParam("projectId") Long projectId) throws Exception {
        try {
            if (!file.isEmpty()) {
                if (!FileUtils.checkAllowDownload(file.getOriginalFilename())) {
                    throw new Exception(StringUtils.format("文件名称({})非法，不允许上传。 ", file.getOriginalFilename()));
                }
                // 上传并返回新文件名称
                String suffixName = FileTypeUtils.getFileType(file);
                String fileName = StringUtils.format("{}_{}_{}.{}",
                        FilenameUtils.getBaseName(file.getOriginalFilename()),
                        SecurityUtils.getUserId(),
                        Seq.getId(Seq.uploadSeqType), suffixName);
                String url = MinIoUtil.upload(minIoProperties.getBucketSafeDoc(), fileName, file.getInputStream());
                AjaxResult ajax = AjaxResult.success();
                ajax.put("url", url);
                ajax.put("fileName", fileName);
                ajax.put("bucket", minIoProperties.getBucketSafeDoc());
                //TODO 工程内业资料入库
                BizSafeDocAttach bizSafeDocAttach = BizSafeDocAttach.builder()
                        .id(IdUtil.getSnowflakeNextId())
                        .bucket(minIoProperties.getBucketSafeDoc())
                        .size(file.getSize())
                        .displayName(FilenameUtils.getBaseName(file.getOriginalFilename()))
                        .realName(fileName)
                        .extName(suffixName)
                        .type(file.getContentType())
                        .projectId(projectId)
                        .build();
                bizSafeDocAttachService.insertBizSafeDocAttach(bizSafeDocAttach);
                Long bizSafeDocAttachId  = bizSafeDocAttach.getId();
                ajax.put("fileId", bizSafeDocAttachId.toString());
                return ajax;
            } else {
                return AjaxResult.error("上传文件不能为空，请联系管理员");
            }
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 教育资料上传
     */
    @PostMapping("/uploadEducateDoc")
    public AjaxResult uploadEducateDoc(@RequestParam("file") MultipartFile file, @RequestParam("projectId") Long projectId) throws Exception {
        try {
            if (!file.isEmpty()) {
                if (!FileUtils.checkAllowDownload(file.getOriginalFilename())) {
                    throw new Exception(StringUtils.format("文件名称({})非法，不允许上传。 ", file.getOriginalFilename()));
                }
                // 上传并返回新文件名称
                String suffixName = FileTypeUtils.getFileType(file);
                String fileName = StringUtils.format("{}_{}_{}.{}",
                        FilenameUtils.getBaseName(file.getOriginalFilename()),
                        SecurityUtils.getUserId(),
                        Seq.getId(Seq.uploadSeqType), suffixName);
                String url = MinIoUtil.upload(minIoProperties.getBucketEdu(), fileName, file.getInputStream());
                BizEducateDocAttach bizEducateDocAttach = BizEducateDocAttach.builder()
                        .id(IdUtil.getSnowflakeNextId())
                        .bucket(minIoProperties.getBucketEdu())
                        .size(file.getSize())
                        .displayName(FilenameUtils.getBaseName(file.getOriginalFilename()))
                        .realName(fileName)
                        .extName(suffixName)
                        .type(file.getContentType())
                        .projectId(projectId)
                        .build();
                bizEducateDocAttachService.insertBizEducateDocAttach(bizEducateDocAttach);
                BizEducateDocAttachVO bizEducateDocAttachVO = new BizEducateDocAttachVO();
                BeanUtils.copyProperties(bizEducateDocAttach,bizEducateDocAttachVO);
                bizEducateDocAttachVO.setUrl(url);
                bizEducateDocAttachVO.setFileId(String.valueOf(bizEducateDocAttachVO.getId()));
                bizEducateDocAttachVO.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
                return AjaxResult.success(bizEducateDocAttachVO);
            } else {
                return AjaxResult.error("上传文件不能为空，请联系管理员");
            }
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

//    public static void main(String[] args) {
//        int length=62;
//        for (int i = 0; i < length; i++) {
//            System.out.println(IdUtil.getSnowflakeNextId());
//        }
//    }
}
